/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/jsx-no-bind */
/**
 * 巴枪设备编号
 *  */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Button, Row, Col, Popconfirm, Table, Select, Spin, message } from 'antd';
import { isLegalData, getLStorage } from '@/utils/utils';
import { isEmpty } from 'lodash';
import styles from '../style.less';

const FormItem = Form.Item;
const { Option } = Select;
const brandMap = {
  zt: {
    name: '中通',
    url: 'allocation/saveDeviceNumberForZt',
  },
  sto: {
    name: '申通',
    url: 'allocation/saveDeviceNumber',
  },
  yd: {
    name: '韵达',
    url: 'allocation/setScanOption',
  },
  yt: {
    name: '圆通',
    url: 'allocation/saveDeviceNumber',
  },
};

@connect(({ allocation, loading, user }) => ({
  allocation,
  userInfo: user.currentUser.user_info,
  getCompanyInfoByBranchCode: loading.effects['allocation/getCompanyInfoByBranchCode'],
  deletSetList: loading.effects['allocation/deletSetList'],
  addSetList: loading.effects['allocation/addSetList'],
}))
@Form.create()
class EquipmentNumber extends PureComponent {
  constructor(props) {
    super(props);
    const { phone, gp_area_ids = [], area_ids } = this.props.userInfo || {};

    const isCompany = area_ids == '*';
    const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
    const area_id = gp_area_ids.includes(cacheAreaId)
      ? cacheAreaId
      : isCompany
        ? '0'
        : gp_area_ids[0];
    this.state = {
      list: [],
      FORM_ITEMS: {},
      gunName: '', // 巴枪设备名称(例如：凯立)
      gunType: '', // 巴枪设备型号(例如：k2)
      area_id,
    };
    const {
      setRecord: { type },
    } = props;
    const commonColums = [
      {
        title: () => (type == 'yd' ? '编号' : '序号'),
        dataIndex: 'number',
        key: 'number',
        align: 'center',
        render: text => (type === 'yd' ? text : 1),
      },
      {
        title: '巴枪设备厂商',
        dataIndex: 'phone_brand',
        key: 'phone_brand',
        align: 'center',
      },
      {
        title: '巴枪设备型号',
        dataIndex: 'divice_type',
        key: 'divice_type',
        align: 'center',
        render: (text, record) => `${record.phone_brand}${record.phone_model}`,
      },
      {
        title: '巴枪设备编号',
        dataIndex: 'device_number',
        key: 'device_number',
        align: 'center',
        render: (text, record) => (type == 'yd' ? record.delivery_gun_code : record.device_number),
      },
      {
        title: '操作',
        align: 'center',
        render: () => (
          <Popconfirm
            placement="top"
            title="是否删除"
            onConfirm={this.delete.bind(this)}
            okText="确定"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        ),
      },
    ];
    switch (type) {
      case 'yd':
        commonColums.splice(1, 2);
        this.columns = commonColums;
        break;
      case 'sto':
        commonColums.splice(1, 1);
        this.columns = commonColums;
        break;
      case 'zt':
      case 'yt':
        commonColums.splice(2, 1);
        this.columns = commonColums;
        break;
      default:
        this.columns = commonColums;
        break;
    }
  }

  componentDidMount() {
    const {
      setRecord: { type },
    } = this.props;
    type === 'yd' ? this.getYdList() : this.getZtStoGunEquipmentList();
    this.renderFormItemByBrand(type);
  }

  componentDidUpdate(prevPros) {
    const {
      setRecord: { type },
      activeKey,
      type: newType,
    } = this.props;
    if (prevPros.activeKey !== activeKey && activeKey == newType) {
      type === 'yd' ? this.getYdList() : this.getZtStoGunEquipmentList();
    }
  }

  onSelect(value, option) {
    this.setState({
      gunName: option.props.name,
      gunType: value,
    });
  }

  // 获取中通、申通巴枪列表
  getZtStoGunEquipmentList() {
    const {
      dispatch,
      setRecord: { type: brandType, branch_code },
    } = this.props;
    const { area_id } = this.state;
    const effectsMap = {
      zt: 'getDeviceNumberListForZt',
      yt: 'getDeviceNumberList',
      sto: 'getDeviceNumberList',
    };
    dispatch({
      type: `allocation/${effectsMap[brandType]}`,
      payload: {
        brand: brandType,
        branch_code,
        area_id,
      },
    }).then(res => {
      const { data } = res;
      let list = [];
      const legalData = isLegalData(data, []);
      if (legalData.length > 0 && legalData[0].device_number) {
        list = [
          {
            ...data[0],
          },
        ];
      }
      this.setState({ list });
    });
  }

  // 获取韵达巴枪列表
  getYdList() {
    const {
      dispatch,
      setRecord: { type, branch_code },
    } = this.props;
    const { area_id } = this.state;
    dispatch({
      type: 'allocation/getCompanyInfoByBranchCode',
      payload: {
        brand: type,
        branch_code,
        area_id,
      },
    }).then(res => {
      const { data } = res;
      let list = [];
      const legalData = isLegalData(data, []);
      if (legalData.length > 0 && legalData[0].delivery_gun_code) {
        list = [
          {
            ...data[0],
            number: '01',
          },
        ];
      }
      this.setState({ list });
    });
  }

  // 申通下拉获取巴枪设备编号
  getGunType(type, visable) {
    const { dispatch } = this.props;
    const { area_id } = this.state;
    visable &&
      dispatch({
        type: 'allocation/getGunType',
        payload: {
          brand: type,
          area_id,
        },
      });
  }

  // 添加巴枪设备编号
  addConfig() {
    const {
      form,
      dispatch,
      setRecord: { type, branch_code, branch_name },
      allocation: { gunNubmerList },
    } = this.props;
    const ydId = !isEmpty(gunNubmerList[0]) ? gunNubmerList[0].id : null;
    const { gunName, gunType, list, area_id } = this.state;
    if (list.length > 0) {
      message.error('不允许添加多个巴枪设备编号');
      return;
    }
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const ydPayload = {
        // 韵达老接口需要的参数
        id: ydId,
        brand: type,
        branch_code,
        arrival_gun_code: fieldsValue.gunNumber,
        delivery_gun_code: fieldsValue.gunNumber,
        area_id,
      };
      const sto_ztPayload = {
        // 申通、中通的参数
        branch_code,
        branch_name,
        brand: type,
        phone_brand: gunName,
        phone_model: gunType,
        device_number: fieldsValue.gunNumber,
        area_id,
      };
      const { url } = brandMap[type];
      const payload = type === 'yd' ? ydPayload : sto_ztPayload;

      dispatch({
        type: url,
        payload,
      }).then(() => {
        type === 'yd' ? this.getYdList() : this.getZtStoGunEquipmentList();
        form.resetFields();
      });
    });
  }

  // 删除巴枪设备编号
  delete() {
    const {
      setRecord: { type, branch_code },
      dispatch,
      // allocation: { gunNubmerList, gunRegisterList },
    } = this.props;
    const { list, area_id } = this.state;
    const id = !isEmpty(list[0]) ? list[0].id : null;
    // const ydId = !isEmpty(gunNubmerList[0]) ? gunNubmerList[0].id : null;
    // const ztStoId = !isEmpty(gunRegisterList[0]) ? gunRegisterList[0].id : null;
    const url = type === 'zt' ? 'deleteDeviceNumberForZt' : 'deleteDeviceNumber';

    type === 'yd' // 后期需要后端统一修改接口后再修改
      ? dispatch({
          type: 'allocation/setScanOption',
          payload: {
            id,
            brand: type,
            branch_code,
            arrival_gun_code: '',
            delivery_gun_code: '',
            area_id,
          },
        }).then(() => {
          this.getYdList();
        })
      : dispatch({
          type: `allocation/${url}`,
          payload: {
            id,
            area_id,
          },
        }).then(() => {
          this.getZtStoGunEquipmentList();
        });
  }

  // 根据品牌来渲染表单元素
  renderFormItemByBrand = type => {
    const brandType = type.toLowerCase();
    const brandName = brandMap[type].name;
    const FORM_ITEMS = {
      gunType: {
        brands: ['sto', 'zt', 'yt'],
        commonRules: [
          {
            required: true,
            message: '请选择巴枪设备型号',
          },
        ],
      },
      help: {
        brands: ['yd'],
      },
      gunNumber: {
        brands: [],
        commonRules: [
          {
            required: true,
            message: `请输入${brandName}巴枪设备编号`,
          },
        ],
        rules: {
          yd: [
            {
              max: 30,
              message: '请输入30位以内的字符！',
            },
          ],
          zt: [
            {
              pattern: /^[0-9a-zA-Z]{1,}$/,
              message: '请输入数字',
            },
          ],
        },
        placeholder: `请输入${brandName}巴枪设备编号`,
      },
    };
    Object.keys(FORM_ITEMS).forEach(key => {
      const element = FORM_ITEMS[key];
      const isAll = element.brands.length === 0;

      element.commonRules &&
        element.rules &&
        element.rules[brandType] &&
        element.commonRules.push(...element.rules[brandType]);
      !element.brands.includes(brandType) && !isAll && delete FORM_ITEMS[key];
    });
    this.setState({
      FORM_ITEMS,
    });
  };

  render() {
    const {
      showDetail,
      form: { getFieldDecorator },
      getCompanyInfoByBranchCode,
      setRecord: { brand, branch_code, type },
      allocation: { gunType },
    } = this.props;
    const { list, FORM_ITEMS } = this.state;

    return (
      <div className={styles.PostOption}>
        <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 24 }}>
          <Col span={18} className={styles.title}>
            <Form layout="inline">
              {FORM_ITEMS.gunType && (
                <FormItem>
                  {getFieldDecorator('gunType', {
                    rules: FORM_ITEMS.gunType.commonRules,
                  })(
                    <Select
                      allowClear
                      style={{ width: 250 }}
                      placeholder="请选择巴枪设备型号"
                      onDropdownVisibleChange={this.getGunType.bind(this, type)}
                      notFoundContent={<Spin size="small" />}
                      onSelect={this.onSelect.bind(this)}
                    >
                      {gunType.map(val => (
                        <Option
                          key={val.type || val.name}
                          value={val.type || val.name}
                          name={val.name}
                        >
                          {val.name + (val.type || '')}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </FormItem>
              )}
              {FORM_ITEMS.gunNumber && (
                <FormItem>
                  {getFieldDecorator('gunNumber', {
                    rules: FORM_ITEMS.gunNumber.commonRules,
                  })(
                    <Input
                      allowClear
                      style={{ width: '350px' }}
                      placeholder={FORM_ITEMS.gunNumber.placeholder}
                    />,
                  )}
                </FormItem>
              )}
              <FormItem>
                <Button
                  loading={getCompanyInfoByBranchCode}
                  type="primary"
                  onClick={this.addConfig.bind(this)}
                >
                  添加编号
                </Button>
              </FormItem>
              {FORM_ITEMS.help && (
                <FormItem>
                  <Button type="primary">帮助</Button>
                </FormItem>
              )}
            </Form>
          </Col>
          <Col span={6}>
            <Row type="flex" align="middle" justify="end">
              <Col>
                <span>{brand}</span>
                <span>（{branch_code}）</span>
              </Col>
              <Col>
                <Button type="primary" onClick={() => showDetail(false)}>
                  返回
                </Button>
              </Col>
            </Row>
          </Col>
        </Row>
        <Table
          className={styles.Tables}
          dataSource={list}
          columns={this.columns}
          rowKey={r => r.id}
          pagination={{ hideOnSinglePage: true }}
          loading={getCompanyInfoByBranchCode}
        />
      </div>
    );
  }
}

export default EquipmentNumber;
